﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Commonlib;
namespace BLL
{
    public class ClothBuyBLL
    {
        private readonly DAL.ItemClothDAL itemclothdal = new DAL.ItemClothDAL();
        private readonly DAL.ClothBuyDAL clothbuydal = new DAL.ClothBuyDAL();
        /// <summary>
        /// 同所选订单的相同布料尺寸加到一起，并为其设置一个referenceNo
        /// </summary>
        public void totalCloth(string clothidlist)
        {
            string cmdstr = "select distinct orderID,companyName,clothNo from ItemClothView where active=1 and ID in(" + clothidlist + ")";
            DataTable dtCloth = SqlHelper.ExecuteDataSet(SqlHelper.SqlConnectionString, CommandType.Text, cmdstr, null).Tables[0];
            //添加新的信息之前 ，要将上次total过但没有发送邮件或没有发送成功的total信息删除掉(布料状态为NoStatus)statusID=1
            SqlHelper.ExecuteNonQuery(SqlHelper.SqlConnectionString,CommandType.Text,"delete from ClothBuy where statusID=1",null);
            foreach (DataRow dr in dtCloth.Rows)
            {
                string orderid = dr["orderID"].ToString();
                string company = dr["companyName"].ToString();
                string clothno = dr["clothNo"].ToString();
                Albon.Model.ClothBuy clothbuy = new Albon.Model.ClothBuy();
                clothbuy.clothRefNo = getClothRef();
                OrderBLL orderbll = new OrderBLL();
                clothbuy.orderRefNo = orderbll.getOrderByID(orderid).Rows[0]["refNo"].ToString();
                clothbuy.clothCompany = company;
                clothbuy.clothNo = clothno;
                cmdstr = "select * from ItemClothView where active=1 and orderID=" + orderid + " and ID in(" + clothidlist + ") and companyName='" + company + "' and clothNo='" + clothno + "'";
                DataTable dtTotal = SqlHelper.ExecuteDataSet(SqlHelper.SqlConnectionString, CommandType.Text, cmdstr, null).Tables[0];
                string list = "";
                foreach (DataRow drTotal in dtTotal.Rows)
                {
                    //获取该布料购买信息所涉及的订单项布料ID列表
                    clothbuy.clothSize += decimal.Parse(drTotal["clothSize"].ToString())*int.Parse(drTotal["quantity"].ToString());
                    
                    if (list=="")
                    {
                        list = drTotal["ID"].ToString();
                    }
                    else
                    {
                        list += "," + drTotal["ID"].ToString();
                    }
                    
                }
                clothbuy.itemClothList = list;
                clothbuydal.addClothBuy(clothbuy);
            }
        }
        /// <summary>
        /// 将汇总后的布料数据统一发送邮件到布料公司，修改布料状态
        /// </summary>
        public string buyCloth(string companyname,string body)
        {
            //邮件发送成功则将itemCloth中的布料信息设为已购买，再将BuyCloth数据设为布料状态设为wait
            if (sendEmail(body))
            {
                Hashtable htlist = getList(companyname);
                string itemclothlist = htlist["itemclothlist"].ToString();
                string buyclothlist = htlist["buyclothlist"].ToString();
                //item cloth
                Albon.Model.ItemCloth itemcloth = new Albon.Model.ItemCloth();
                itemcloth.statusID = 2;
                itemcloth.purchaser = System.Web.HttpContext.Current.User.Identity.Name;
                itemcloth.buyRemark = "Finished Sending Email!";
                itemclothdal.buyCloth(itemclothlist, itemcloth);
                //cloth buy
                clothbuydal.buyCloth(buyclothlist);
                return "Finish Buy";
            }
            else
            {
                return "Send Fail";
            }
        }
        //获取已完成发送的BuyCloth数据的id列表 
        private Hashtable getList(string companyname)
        {
            string cmdstr = "select * from ClothBuy where clothCompany='" + companyname + "' and statusID=1";
            DataTable dt = SqlHelper.ExecuteDataSet(SqlHelper.SqlConnectionString, CommandType.Text, cmdstr, null).Tables[0];
            string itemclothlist = "";
            string buyclothlist = "";
            Hashtable ht = new Hashtable();
            foreach (DataRow dr in dt.Rows)
            {
                itemclothlist += dr["itemClothList"].ToString() + ",";
                buyclothlist += dr["ID"].ToString() + ",";
            }
            if (itemclothlist.Length > 0)
            {
                itemclothlist = itemclothlist.Substring(0, itemclothlist.Length - 1);
            }
            if (buyclothlist.Length > 0)
            {
                buyclothlist = buyclothlist.Substring(0,buyclothlist.Length-1);
            }
            ht.Add("itemclothlist", itemclothlist);
            ht.Add("buyclothlist", buyclothlist);
            return ht;
        }
        //发送邮件
        private bool sendEmail(string body)
        {
            string fromEmail="vinlon@albon.com.hk";
            string fromPsw="lwlfly";
            string toEmail="datou-1009@163.com";
            string subject="Albon Fabric Order";
            return EmailHelper.SendEmail(fromEmail, fromPsw, toEmail, subject, body, null);
        }

        //生成布料的refNo(日期加当天布料的序号)
        private string getClothRef()
        {
            string date =DateTime.Today.ToString("yyMMdd");
            string seq = (clothbuydal.getClothBuy("createDate>'"+DateTime.Today+"'").Rows.Count+1).ToString();
            return date + seq;
        }
        /// <summary>
        /// 修改汇总后的布料购买信息的布料状态 （要先修改相应的订单布料的状态）
        /// </summary>
        public void updateStatus(string idlist,string statusID,string statusName,string username)
        {
            DataTable dt=clothbuydal.getClothBuy("ID in ("+idlist+")");
            foreach (DataRow dr in dt.Rows)
            { 
                //先修改订单项布料表（ItemClot）中的布料信息
                DAL.ItemClothDAL itemclothdal = new DAL.ItemClothDAL();
                string statusRemark = DateTime.Now.ToString("yyyy-MM-dd") + " Moved to " + statusName + " By " + username + "<br>";
                itemclothdal.updateStatus(dr["itemClothList"].ToString(),statusID, statusRemark);
                //再修改ClothBuy表中的状态 
                clothbuydal.updateStatus(dr["ID"].ToString(),statusID);
            }
        }
    }
}
